package com.kadron.datamodel;

import java.util.List;

import javax.persistence.EntityManager;

import com.kadron.dao.KOrderDAO;
import com.kadron.entity.Item;

public class KOrderModelDataProvider implements KDataProvider {

	/**
	 * 
	 */
	private static final long serialVersionUID = -4707252300895840420L;
	
	private KModelCreator creator;
	private KOrderDAO orderDAO;
	private long userId;
	
	public KOrderModelDataProvider(long userId,KModelCreator creator,KOrderDAO orderDAO) {
		super();
		this.creator = creator;
		this.userId = userId;
		this.orderDAO = orderDAO;
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Long> getItemsByRange(Integer integer, int numberOfRows,
			Object object, boolean b) {
		EntityManager em = orderDAO.getEntityManager();
		return em.createQuery("SELECT a.id FROM Order a WHERE a.user.id=:userId ORDER BY a.id DESC")
			.setParameter("userId", userId)
			.setFirstResult(integer)
			.setMaxResults(numberOfRows).getResultList();
	}

	@Override
	public KModel getItemById(Long id, KModelCreator creator) {
		return creator.create(id);
	}

	@Override
	public int getRowCount() {
		EntityManager em = orderDAO.getEntityManager();
		Long count = (Long) em.createQuery("SELECT COUNT(a.id) FROM Order a WHERE a.user.id=:userId").setParameter("userId", userId).getSingleResult();
		return (count == null) ? 0 : count.intValue() ;
	}

	@Override
	public boolean hasItemWithId(Long id) {
		return orderDAO.exists(id, Item.class);
	}

	@Override
	public KModelCreator getCreator() {
		return creator;
	}

}
